<template>
    <view class="container">
        <view class="title">拨号盘</view>
        
        <view class="input-section">
            <text>您的号码：</text>
            <input 
                v-model="myPhone" 
                type="number" 
                placeholder="输入您的手机号"
                maxlength="11"
                disabled
            />
        </view>

        <view class="input-section">
            <text>请选择虚拟号码：</text>
            <picker class="picker" @change="onVirtualNumberChange" :value="virtualNumberIndex" :range="virtualNumbers" range-key="virtualNumber">
                <view class="picker-view">{{ selectedVirtualNumber || '请选择虚拟号码' }}</view>
            </picker>
        </view>
        
        <view class="input-section">
            <text>请输入要呼叫的号码：</text>
            <input 
                v-model="targetPhone" 
                type="number" 
                placeholder="输入目标手机号"
                maxlength="11"
            />
        </view>
        
        <button 
            class="call-btn" 
            @click="startCall"
            :disabled="!myPhone || !targetPhone || !selectedVirtualNumber"
        >
            开始呼叫
        </button>
    </view>
</template>

<script>
import websocket from '@/common/websocket.js'

export default {
    data() {
        return {
            myPhone: '',
            targetPhone: '',
            virtualNumbers: [],
            virtualNumberIndex: 0,
            selectedVirtualNumber: ''
        };
    },
    onLoad() {
        // 页面加载时获取用户信息和虚拟号码列表
        this.fetchUserInfo();
        this.fetchVirtualNumbers();
    },
    methods: {
        // 获取用户信息
        fetchUserInfo() {
            // 从本地存储获取用户手机号
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo && userInfo.phone) {
                this.myPhone = userInfo.phone;
            }
        },
        
        // 获取虚拟号码列表
        async fetchVirtualNumbers() {
            try {
                // 从本地存储获取用户手机号
                const userInfo = uni.getStorageSync('userInfo');
                if (!userInfo || !userInfo.phone) {
                    uni.showToast({
                        title: '未找到用户信息',
                        icon: 'none'
                    });
                    return;
                }
                
                // 调用API获取虚拟号码列表
                const response = await this.getVirtualNumbersByPhone(userInfo.phone);
                
                if (response.code === 0) {
                    // 过滤出启用状态的虚拟号码
                    this.virtualNumbers = response.data.filter(item => item.status === 1);
                    
                    // 默认选择第一个虚拟号码
                    if (this.virtualNumbers.length > 0) {
                        this.selectedVirtualNumber = this.virtualNumbers[0].virtualNumber;
                    }
                } else {
                    uni.showToast({
                        title: response.msg || '获取虚拟号码列表失败',
                        icon: 'none'
                    });
                }
            } catch (error) {
                console.error('获取虚拟号码列表异常:', error);
                uni.showToast({
                    title: '网络请求异常',
                    icon: 'none'
                });
            }
        },
        
        // 调用获取虚拟号码接口
        getVirtualNumbersByPhone(phoneNumber) {
            return new Promise((resolve, reject) => {
                uni.request({
                    url: 'http://localhost:6002/user-client/api/virtualNumber/getByPhoneNumber?phoneNumber=' + phoneNumber,
                    method: 'POST',
                    header: {
                        'Content-Type': 'application/json'
                    },
                    success: (res) => {
                        resolve(res.data);
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        },
        
        // 虚拟号码选择变更处理
        onVirtualNumberChange(e) {
            this.virtualNumberIndex = e.detail.value;
            this.selectedVirtualNumber = this.virtualNumbers[this.virtualNumberIndex].virtualNumber;
        },
        
        startCall() {
            // 保存当前号码到本地
            uni.setStorageSync('myPhone', this.myPhone);
            
            // 检查WebSocket连接状态，如果未连接则重新连接
            if (!websocket.isConnected) {
                websocket.init(this.myPhone);
            }
            
            // 跳转到通话页面，状态为dialing（拨号中）
            uni.navigateTo({
                url: `/pages/call/call?myPhone=${this.myPhone}&targetPhone=${this.targetPhone}&virtualNumber=${this.selectedVirtualNumber}&callState=dialing`
            });
        }
    }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    padding: 20rpx;
}

.title {
    font-size: 36rpx;
    text-align: center;
    margin: 50rpx 0;
    font-weight: bold;
}

.input-section {
    margin-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    gap: 10rpx;
}

.input-section text {
    font-size: 28rpx;
}

.input-section input {
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
}

.input-section input:disabled {
    background-color: #f5f5f5;
    color: #999;
}

.picker {
    height: 80rpx;
    border: 1px solid #ddd;
    border-radius: 10rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    line-height: 80rpx;
    background-color: #fff;
}

.picker-view {
    line-height: 80rpx;
    color: #333;
}

.call-btn {
    background-color: #007aff;
    color: white;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    margin-top: 50rpx;
}

.call-btn:disabled {
    background-color: #ccc;
}
</style>